package com.aaxis.microservice.training.demo1.config;

import com.aaxis.microservice.training.demo1.security.MyAccessDeniedHandler;
import com.aaxis.microservice.training.demo1.security.MyAuthenctiationFailureHandler;
import com.aaxis.microservice.training.demo1.security.MyAuthenctiationSuccessHandler;
import com.aaxis.microservice.training.demo1.security.MyAuthenticationProvider;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.configurers.ExpressionUrlAuthorizationConfigurer;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import javax.annotation.Resource;

@Configuration
@EnableWebSecurity
public class URLSecurityConfiguration extends WebSecurityConfigurerAdapter {
    @Resource
    private MyAuthenctiationSuccessHandler myAuthenctiationSuccessHandler;
    @Resource
    private MyAuthenctiationFailureHandler myAuthenctiationFailureHandler;
    @Resource
    private MyAuthenticationProvider provider;
    @Resource
    private MyAccessDeniedHandler myAccessDeniedHandler;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
//        ((HttpSecurity)((HttpSecurity)((ExpressionUrlAuthorizationConfigurer.AuthorizedUrl)http.authorizeRequests()
//                .anyRequest()).authenticated().and()).formLogin().and()).httpBasic();
        http.formLogin()
                .loginPage("/login")
                .loginProcessingUrl("/doLogin")
                .permitAll()
                .failureUrl("/login?failed=true")
                .defaultSuccessUrl("/index")
//                .successHandler(myAuthenctiationSuccessHandler)
//                .failureHandler(myAuthenctiationFailureHandler)
                .and()
                .authorizeRequests()
                .antMatchers("/login","/regist").permitAll()
                .anyRequest().authenticated()
                .and().exceptionHandling().accessDeniedHandler(myAccessDeniedHandler)
                .and().httpBasic().and().csrf().disable();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(provider);
    }

    @Bean(name = "bCryptPasswordEncoder")
    public BCryptPasswordEncoder bCryptPasswordEncoder(){
        return new BCryptPasswordEncoder();
    }
}
